package com.twu.biblioteca;

import com.twu.biblioteca.book.Book;
import com.twu.biblioteca.book.BookManager;
import com.twu.biblioteca.command.Command;
import com.twu.biblioteca.command.CommandFactory;
import com.twu.biblioteca.command.NeedLogin;
import com.twu.biblioteca.command.Option;
import com.twu.biblioteca.movie.Movie;
import com.twu.biblioteca.movie.MovieManager;
import com.twu.biblioteca.user.UserInfo;
import com.twu.biblioteca.util.IO;
import com.twu.biblioteca.util.UserAccountValidator;

import java.io.*;
import java.util.HashMap;
import java.util.List;


public class Library {

    public static UserInfo currentUser;
    private BookManager bookManager;
    private MovieManager movieManager;
    private IO io;

    private boolean quit = false;

    public Library(BookManager bookManager, MovieManager movieManager) {
        this.bookManager = bookManager;
        this.movieManager = movieManager;
    }

    public void executeOption(String userOption) throws Exception {
        Command command = CommandFactory.createCommand(userOption);
        if (command instanceof NeedLogin) {
            new UserAccountValidator().validate(this);
        }
        command.execute(this);
    }

    public void setQuit() {
        this.quit = true;
    }

    public boolean isQuit() {
        return quit;
    }

    public BookManager getBookManager() {
        return bookManager;
    }

    public void showOptions() {
        HashMap<Option, Command> options = CommandFactory.getOptions();
        showMessage("Input the following number to select option:");
        for (Option option : options.keySet()) {
             showMessage(option.getCode() + " " + option.getDescription());
        }
    }

    public void showBooks() {
        List<Book> bookList = bookManager.getBooks();
        for (Book book : bookList) {
            showMessage(book.toString());
        }
    }

    public void showMovie() {
        HashMap<Movie,Integer> movies = movieManager.getMovies();
        showMessage(movieManager.format());
        for (Movie movie : movies.keySet()) {
            showMessage(movie.toString());
        }
    }

    public void showMessage(String message) {
        io.write(message);
    }

    public String getMessage() {
        return io.readLine();
    }

    public void setIO(InputStream inputStream, OutputStream outputStream) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream));
        this.io = new IO(reader, writer);
    }
}
